package bank.service.impl.impl;

import bank.mapper.AccountMapper;
import bank.pojo.Account;
import bank.service.impl.AccountService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service("accountService")
@Transactional()
public class AccountServiceImpl implements AccountService {

    @Autowired
    private AccountMapper accountMapper;
    @Override
    public int save(Account act) {
        return accountMapper.insert(act);
    }

    @Override
    public int deleteByAct(String actno) {
        return accountMapper.deleteByActno(actno);
    }

    @Override
    public int modifyByActno(Account act) {
        return accountMapper.update(act);
    }

    @Override
    public Account getByActno(String actno) {
        return accountMapper.selectByActno(actno);
    }

    @Override
    public List<Account> getAll() {
        return accountMapper.selectAll();
    }

    @Override
    public void transfer(String fromAct, String toAct, double moneny) {
        Account fromAccount = accountMapper.selectByActno(fromAct);
        if(fromAccount.getBalance()<moneny){
            throw new RuntimeException("余额不足");
        }
        Account toAccount = accountMapper.selectByActno(toAct);
        fromAccount.setBalance(fromAccount.getBalance()-moneny);
        toAccount.setBalance(toAccount.getBalance()+moneny);
        int update=accountMapper.update(fromAccount);
        update+=accountMapper.update(toAccount);
        if(update!=2){

            throw new RuntimeException("转账失败，联系银行！");
        }


    }


}
